package ch.ethz.inf.shop.model.simpleDatabase.operators;

import ch.ethz.inf.shop.model.simpleDatabase.Tuple;

/**
 * Selection in relational algebra. Only returns those tuple for which the given
 * column matches the value.
 * 
 * This class is a generic to allow comparing any types of values.
 * 
 * i.e. SELECT * FROM USERS WHERE USER_ID=1 would require these operators:
 * 
 * Scan usersScanOperator = new Scan(filename, columnNames); Select<Integer>
 * selectOp = new Select<Integer>( usersScanOperator, "user_id", 1);
 * 
 * Similarly, this query:
 * 
 * SELECT * FROM USERS WHERE USENAME=john would require these operators:
 * 
 * Scan usersScanOperator = new Scan(filename, columnNames); Select<String>
 * selectOp = new Select<String>( usersScanOperator, "username", "john");
 * 
 */
public class Select extends Operator {

	private final Operator op;
	private final TupleAccepter accepter;

	public Select(final Operator op, TupleAccepter comparator) {
		if (this == op)
			throw new RuntimeException("Operators cannot be used recursively");
		this.op = op;
		this.accepter = comparator;
	}

	@Override
	public boolean moveNext() {

		// a) retrieve the next tuple from the child operator
		while (op.moveNext()) {
			final Tuple t = this.op.current();
			// c) check if this tuple matches our selection predicate
			if (accepter.acceptTuple(t)) {
				// It does
				this.current = t;
				return true;
			}
		}
		return false;
	}
}
